package org.swimv2.servlets;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.swimv2.entities.Job;
import org.swimv2.entities.Skill;
import org.swimv2.entities.User;
import org.swimv2.interfaces.JobsManagerRemote;
import org.swimv2.interfaces.SearchManagerRemote;
import org.swimv2.interfaces.SkillManagerRemote;
import org.swimv2.utils.ContextUtil;

/**
 * Servlet implementation class RequestHelpServlet
 */
public class RequestHelpServlet extends HttpServlet {
       
	private static final long serialVersionUID = 7788367257107842549L;
	
	private User page_u, curr_u;
	
	private SearchManagerRemote mgr_u = null;
	private JobsManagerRemote   mgr_j = null;
	private SkillManagerRemote  mgr_s = null;


	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RequestHelpServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * Invia una richiesta di aiuto lavorativo all'utente selezionato.
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		try {
			Context ctx = ContextUtil.getInitialContext();
			mgr_u = (SearchManagerRemote) ctx.lookup("SearchManagerJNDI");
			mgr_s = (SkillManagerRemote)  ctx.lookup("SkillManagerJNDI");
			mgr_j = (JobsManagerRemote)   ctx.lookup("JobsManagerJNDI");
			
			RequestDispatcher disp;
			disp = request.getRequestDispatcher("/WEBswim2/home.jsp");
			
			// L'utente loggato
			curr_u = (User) request.getSession().getAttribute("user");
			// L'utente da visualizzare
			page_u = mgr_u.getUserById(Integer.parseInt(request.getParameter("user_id")));
			
			/* Controllo correttezza parametri utente */
			if (page_u == null || curr_u == null || curr_u.getId() == page_u.getId()) {
				request.setAttribute("error_message", "Errore: utente non corretto.");
				disp.forward(request, response);
				return;
			}
			
			disp = request.getRequestDispatcher("user/profile.jsp");

			/* Controllo parametri richiesta di lavoro */
			String param_desc  = request.getParameter("desc");
			String param_place = request.getParameter("place");
			Skill  param_skill = mgr_s.getSkill(Integer.parseInt(request.getParameter("skill_id")));
			int    param_pay   = Integer.parseInt(request.getParameter("pay"));
			int    param_day   = Integer.parseInt(request.getParameter("day"));
			int    param_month = Integer.parseInt(request.getParameter("month"));
			int    param_year  = Integer.parseInt(request.getParameter("year"));
			Date   start_date  = null;
			try {
				SimpleDateFormat parser = new SimpleDateFormat("d M yyyy");
				start_date  = parser.parse(param_day +" "+ param_month +" "+ param_year);
			} catch (ParseException e) { e.printStackTrace(); }
			
			if ( param_pay < 0 || param_place == null || param_skill == null || 
				 param_place.length() <= 0 || start_date == null)
				// FIXME !page_u.getSkills().contains(param_skill)
			{
				disp = request.getRequestDispatcher("user/profile.jsp");
				request.setAttribute("error_message", "Errore: lavoro non compilato correttamente.");
				disp.forward(request, response);
				return;
			}
			
			Job j = new Job();
			j.setClient(curr_u);
			j.setWorker(page_u);
			j.setDescription(param_desc);
			j.setPlace(param_place);
			j.setSkill(param_skill);
			j.setPay(param_pay);
			j.setStartDate(start_date);
			
			if ( mgr_j.sendHelpReq(curr_u, page_u, param_desc, param_place, param_skill, param_pay, start_date) )
				request.setAttribute("message", "Richiesta inviata!");
			else
				request.setAttribute("error_message", "Errore nell'invio della richiesta di lavoro.");
			
			// Effettua il redirect
			disp.forward(request, response);
		}
		catch (NamingException e) {
			e.printStackTrace();
		}
	}

}
